import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/common/MyAchievement.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:intl/intl.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';

class BadgesDataGrids extends StatefulWidget {
  @override
  State<BadgesDataGrids> createState() => _BadgesDataGridsState();
}

class _BadgesDataGridsState extends State<BadgesDataGrids> {
  final UserController _userController = Get.find();
  final box = Hive.box('appconfig');
  List<MyAchievement> myAchievements = [];
  bool isWebOrDesktop =
      GetPlatform.isMacOS || GetPlatform.isWeb || GetPlatform.isDesktop;
  List<DataGridRow> dataGridRows = <DataGridRow>[];
  DataGridController _dataGridController = DataGridController();

  @override
  void initState() {
    bool isIndividualOrStudent =
        box.get(CacheManagerKey['nanhairole'].toString()) ==
                Constants.NanhaiRole_Individual ||
            box.get(CacheManagerKey['nanhairole'].toString()) ==
                Constants.NanhaiRole_Student;

    if (_userController.achievements.isEmpty && isIndividualOrStudent) {
      Future.delayed(Duration(milliseconds: 200), () {
        _userController.getProfile();
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build BadgesDataGrids');

    return Obx(() {
      if (_userController.achievements.isNotEmpty) {
        myAchievements = _userController.achievements;
        return _buildDataGrid();
      } else {
        return Center(child: Text('No badge ... '.tr));
      }
    });
  }

  SfDataGrid _buildDataGrid() {
    return SfDataGrid(
      source: BadgesDataGridSource(items: myAchievements),
      controller: _dataGridController,
      onQueryRowHeight: (details) {
        return details.getIntrinsicRowHeight(details.rowIndex);
      },
      allowSorting: true,
      allowTriStateSorting: true,
      allowSwiping: false,
      selectionMode: SelectionMode.single,
      navigationMode: GridNavigationMode.row,
      columnWidthMode: ColumnWidthMode.auto,
      columnWidthCalculationRange: ColumnWidthCalculationRange.allRows,
      columns: <GridColumn>[
        GridColumn(
          width: isWebOrDesktop ? 200 : 150,
          columnName: 'Image',
          label: buildDataGridColumnLabel(''),
        ),
        GridColumn(
          columnName: 'Badge',
          width: isWebOrDesktop ? 200 : 180,
          label: buildDataGridColumnLabel('Badge'),
        ),
        GridColumn(
          columnName: 'Description',
          width: isWebOrDesktop ? 350.0 : 280.0,
          label: buildDataGridColumnLabel('Description'),
        ),
        GridColumn(
          columnName: 'DateEarned',
          width: 140,
          label: buildDataGridColumnLabel('Date Earned'),
        ),
        GridColumn(
          columnName: 'Id',
          width: 10,
          visible: false,
          label: buildDataGridColumnLabel('Id'),
        ),
      ],
    );
  }
}

class BadgesDataGridSource extends DataGridSource {
  BadgesDataGridSource({required List<MyAchievement> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'Image', value: dataGridRow.achievement?.image),
              DataGridCell<String>(
                  columnName: 'Badge', value: dataGridRow.achievement?.name),
              DataGridCell<String>(
                  columnName: 'Description',
                  value: dataGridRow.achievement?.description),
              DataGridCell<int>(
                  columnName: 'DateEarned', value: dataGridRow.when),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'DateEarned') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '',
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else if (dataGridCell.columnName == 'Image') {
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Image.network(
                dataGridCell.value,
                //fit: BoxFit.cover,
              ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
